/*
 * @Author: Await
 * @Date: 2025-04-17 17:15:25
 * @LastEditors: Await
 * @LastEditTime: 2025-05-06 16:12:06
 * @Description: 编辑器主组件
 */
import React, { createContext, useContext, useReducer } from 'react';
// 导入 Antd Layout 组件
import { Layout } from 'antd';

import EditorPanel from './EditorPanel';
import PreviewPanel from './PreviewPanel';
import { ChartConfig, EditorState, ChartType, DataItem, DataConfig } from '../../types/index';

const { Sider, Content } = Layout;

// 初始状态
const initialState: EditorState = {
    currentChart: {
        type: ChartType.BAR,
        title: {
            show: true,
            text: '图表标题',
            subtext: '',
            position: { left: 'center' },
            textStyle: { color: '#333', fontSize: 18 }
        },
        legend: {
            show: true,
            orient: 'horizontal',
            position: { left: 'center', top: 'bottom' },
            textStyle: { color: '#333', fontSize: 12 }
        },
        series: [
            {
                name: '系列1',
                itemStyle: { color: '#5470c6' }
            }
        ],
        axis: {
            xAxisLabel: {
                show: true,
                rotate: 0,
                color: '#333333',
                fontSize: 12
            },
            yAxisLabel: {
                show: true,
                rotate: 0,
                color: '#333333',
                fontSize: 12
            }
        }
    },
    dataSource: {
        data: [
            { name: '类别1', value: 120 },
            { name: '类别2', value: 200 },
            { name: '类别3', value: 150 },
            { name: '类别4', value: 80 },
            { name: '类别5', value: 70 }
        ],
        loading: false,
        error: null
    },
    dataConfig: {
        dimensions: [
            { field: 'name', name: '类别', xAxis: true }
        ],
        measures: [
            { field: 'value', name: '数值' }
        ]
    },
    history: {
        past: [],
        future: []
    },
    loading: false,
    error: undefined,
    previewMode: false,
    editingPart: 'config'
};

// 编辑器Context
type EditorContextType = {
    state: EditorState;
    dispatch: React.Dispatch<EditorAction>;
};

const EditorContext = createContext<EditorContextType | undefined>(undefined);

// 创建操作类型
type EditorAction =
    | { type: 'UPDATE_CHART'; payload: Partial<ChartConfig> }
    | { type: 'SWITCH_CHART_TYPE'; payload: ChartType }
    | { type: 'UPDATE_DATA'; payload: DataItem[] }
    | { type: 'UPDATE_DATA_CONFIG'; payload: DataConfig }
    | { type: 'UNDO' }
    | { type: 'REDO' }
    | { type: 'RESET_CONFIG' }
    | { type: 'IMPORT_CONFIG'; payload: string }
    | { type: 'TOGGLE_PREVIEW_MODE' }
    | { type: 'SET_EDITING_PART'; payload: 'config' | 'data' }
    | { type: 'SET_LOADING'; payload: boolean }
    | { type: 'SET_ERROR'; payload: string | null };

// 编辑器状态reducer
const editorReducer = (state: EditorState, action: EditorAction): EditorState => {
    switch (action.type) {
        case 'UPDATE_CHART': {
            // 保存历史状态
            const newPast = [...state.history.past, state.currentChart];

            // 更新图表配置
            const newChart = { ...state.currentChart, ...action.payload };

            // 记录更新日志，帮助调试
            console.log('编辑器更新图表配置:', {
                before: state.currentChart,
                changes: action.payload,
                after: newChart
            });

            // 特别检查Y轴标签formatter
            if (action.payload.axis?.yAxisLabel?.formatter) {
                console.log('UPDATE_CHART: Y轴标签formatter已更新为:',
                    action.payload.axis.yAxisLabel.formatter);
            }

            return {
                ...state,
                currentChart: newChart,
                history: {
                    past: newPast,
                    future: [] // 清空撤销历史
                }
            };
        }

        case 'SWITCH_CHART_TYPE': {
            // 保存历史状态
            const newPast = [...state.history.past, state.currentChart];

            // 获取当前类型和目标类型
            const currentType = state.currentChart.type;
            const targetType = action.payload;

            // 判断是否在2D和3D之间切换
            const currentIs3D = currentType.includes('3D');
            const targetIs3D = targetType.includes('3D');

            // 准备新的图表配置
            let newChart: ChartConfig = {
                ...state.currentChart,
                type: targetType
            };

            // 处理网格配置转换
            if (currentIs3D !== targetIs3D) {
                // 从2D到3D或从3D到2D时，保留适当的网格配置
                const { grid } = state.currentChart;
                let newGrid = { ...grid };

                if (targetIs3D) {
                    // 2D到3D：添加3D特有属性
                    newGrid = {
                        ...newGrid,
                        boxWidth: newGrid.boxWidth || 200,
                        boxDepth: newGrid.boxDepth || 80,
                        boxHeight: newGrid.boxHeight || 100
                    };
                } else {
                    // 3D到2D：移除3D特有属性
                    if (newGrid) {
                        const { boxWidth, boxDepth, boxHeight, ...rest } = newGrid;
                        newGrid = rest;
                    }
                }

                newChart.grid = newGrid;
            }

            // 处理系列数据转换
            if (newChart.series && newChart.series.length > 0) {
                newChart.series = newChart.series.map(series => {
                    // 创建新的系列对象，但保持数据不变
                    const newSeries = { ...series };

                    // 更新系列类型以匹配图表类型
                    if (series.type) {
                        newSeries.type = targetType;
                    }

                    // 根据目标图表类型调整特定属性
                    if (targetIs3D) {
                        // 添加3D图表可能需要的属性
                        newSeries.shading = newSeries.shading || 'color';

                        // 为3D图表添加默认数据格式配置
                        if (targetType === 'bar3D') {
                            newSeries.bevelSize = 0.2;
                            newSeries.bevelSmoothness = 2;
                        } else if (targetType === 'scatter3D') {
                            newSeries.symbolSize = 12;
                            newSeries.emphasis = {
                                itemStyle: {
                                    color: '#f58220',
                                    borderWidth: 1,
                                    borderColor: '#fff'
                                }
                            };
                        } else if (targetType === 'line3D') {
                            newSeries.lineStyle = {
                                width: 4,
                                color: '#f58220'
                            };
                        }
                    } else {
                        // 移除3D特有属性
                        if (newSeries.shading) {
                            const { shading, bevelSize, bevelSmoothness, ...rest } = newSeries;
                            return rest;
                        }
                    }

                    return newSeries;
                });
            }

            // 处理坐标轴配置转换
            if (targetIs3D && !currentIs3D) {
                // 2D到3D：确保有Z轴配置
                if (!newChart.axis) {
                    newChart.axis = {};
                }

                // 添加Z轴配置
                if (!newChart.axis.zAxisLabel) {
                    newChart.axis.zAxisLabel = {
                        show: true,
                        rotate: 0,
                        color: '#333333',
                        fontSize: 12
                    };
                }

                if (!newChart.axis.zAxisLine) {
                    newChart.axis.zAxisLine = { show: true };
                }

                if (!newChart.axis.zAxisTick) {
                    newChart.axis.zAxisTick = { show: true };
                }

                if (!newChart.axis.zSplitLine) {
                    newChart.axis.zSplitLine = { show: true };
                }

                // 添加3D特有配置
                newChart.viewControl = newChart.viewControl || {
                    autoRotate: false,
                    zoomSensitivity: 1,
                    alpha: 30,
                    beta: 30
                };

                newChart.light = newChart.light || {
                    main: { intensity: 1, shadow: false },
                    ambient: { intensity: 0.2 }
                };
            } else if (!targetIs3D && currentIs3D) {
                // 3D到2D：移除3D特有配置
                if (newChart.viewControl) {
                    const { viewControl, ...rest } = newChart;
                    newChart = rest;
                }

                if (newChart.light) {
                    const { light, ...rest } = newChart;
                    newChart = rest;
                }

                // 移除Z轴配置(可选，保留也不影响2D图表)
                if (newChart.axis) {
                    const { zAxisLabel, zAxisLine, zAxisTick, zSplitLine, zAxisName, zAxisGeneral, ...rest } = newChart.axis;
                    newChart.axis = rest;
                }
            }

            return {
                ...state,
                currentChart: newChart,
                history: {
                    past: newPast,
                    future: []
                }
            };
        }

        case 'UPDATE_DATA': {
            return {
                ...state,
                dataSource: {
                    ...state.dataSource,
                    data: action.payload
                }
            };
        }

        case 'UPDATE_DATA_CONFIG': {
            return {
                ...state,
                dataConfig: action.payload
            };
        }

        case 'UNDO': {
            if (state.history.past.length === 0) return state;

            // 获取上一个状态
            const previous = state.history.past[state.history.past.length - 1];
            const newPast = state.history.past.slice(0, -1);

            return {
                ...state,
                currentChart: previous,
                history: {
                    past: newPast,
                    future: [state.currentChart, ...state.history.future]
                }
            };
        }

        case 'REDO': {
            if (state.history.future.length === 0) return state;

            // 获取下一个状态
            const next = state.history.future[0];
            const newFuture = state.history.future.slice(1);

            return {
                ...state,
                currentChart: next,
                history: {
                    past: [...state.history.past, state.currentChart],
                    future: newFuture
                }
            };
        }

        case 'RESET_CONFIG': {
            return {
                ...state,
                currentChart: initialState.currentChart,
                history: {
                    past: [...state.history.past, state.currentChart],
                    future: []
                }
            };
        }

        case 'IMPORT_CONFIG': {
            try {
                const config = JSON.parse(action.payload);

                return {
                    ...state,
                    currentChart: config,
                    history: {
                        past: [...state.history.past, state.currentChart],
                        future: []
                    }
                };
            } catch (error) {
                return {
                    ...state,
                    error: '导入配置失败，请检查配置格式'
                };
            }
        }

        case 'TOGGLE_PREVIEW_MODE': {
            return {
                ...state,
                previewMode: !state.previewMode
            };
        }

        case 'SET_EDITING_PART': {
            return {
                ...state,
                editingPart: action.payload
            };
        }

        case 'SET_LOADING': {
            return {
                ...state,
                loading: action.payload
            };
        }

        case 'SET_ERROR': {
            return {
                ...state,
                error: action.payload
            };
        }

        default:
            return state;
    }
};

// 编辑器Provider组件
interface EditorProviderProps {
    children: React.ReactNode;
    initialConfig?: ChartConfig;
    initialData?: DataItem[];
}

export const EditorProvider: React.FC<EditorProviderProps> = ({
    children,
    initialConfig,
    initialData
}) => {
    // 合并初始配置和数据
    const mergedInitialState = {
        ...initialState,
        currentChart: initialConfig || initialState.currentChart,
        dataSource: {
            ...initialState.dataSource,
            data: initialData || initialState.dataSource.data
        }
    };

    // 使用useReducer管理状态
    const [state, dispatch] = useReducer(editorReducer, mergedInitialState);

    // 创建Context值
    const contextValue = { state, dispatch };

    return (
        <EditorContext.Provider value={contextValue}>
            {children}
        </EditorContext.Provider>
    );
};

// 自定义Hook，用于访问编辑器状态和操作
export const useEditor = () => {
    const context = useContext(EditorContext);

    if (!context) {
        throw new Error('useEditor必须在EditorProvider内使用');
    }

    const { state, dispatch } = context;

    // 更新图表配置
    const updateChart = (config: Partial<ChartConfig>) => {
        // 如果这是DataMapping组件触发的更新，不再触发额外的更新
        if (config._updatedByDataMapping) {
            // 移除标记以避免污染状态
            const { _updatedByDataMapping, ...restConfig } = config;
            console.log('来自DataMapping的图表更新，应用变更');
            dispatch({ type: 'UPDATE_CHART', payload: restConfig });
            return;
        }

        console.log('更新图表配置:', config);
        // 检查Y轴标签formatter是否存在
        if (config.axis?.yAxisLabel?.formatter) {
            console.log('Y轴标签formatter将被设置为:', config.axis.yAxisLabel.formatter);
        }
        dispatch({ type: 'UPDATE_CHART', payload: config });
    };

    // 切换图表类型
    const switchChartType = (type: ChartType) => {
        console.log('切换图表类型:', type);
        // 在切换图表类型前先设置加载状态
        dispatch({ type: 'SET_LOADING', payload: true });

        // 延迟执行图表类型切换，确保加载状态UI得到渲染
        setTimeout(() => {
            dispatch({ type: 'SWITCH_CHART_TYPE', payload: type });

            // 切换完成后取消加载状态
            setTimeout(() => {
                dispatch({ type: 'SET_LOADING', payload: false });

                // 图表类型切换后，检查是否存在多组数据
                // 这个标志会在DataMapping组件的useEffect中检测到变化
                // 从而触发多组数据的重新渲染
                dispatch({
                    type: 'UPDATE_CHART',
                    payload: {
                        _multiDataGroupsUpdated: new Date().getTime()
                    }
                });
            }, 500);
        }, 100);
    };

    // 更新数据
    const updateData = (data: DataItem[]) => {
        dispatch({ type: 'UPDATE_DATA', payload: data });
    };

    // 更新数据配置
    const updateDataConfig = (config: DataConfig) => {
        dispatch({ type: 'UPDATE_DATA_CONFIG', payload: config });
    };

    // 撤销操作
    const undo = () => {
        dispatch({ type: 'UNDO' });
    };

    // 重做操作
    const redo = () => {
        dispatch({ type: 'REDO' });
    };

    // 重置配置
    const resetConfig = () => {
        dispatch({ type: 'RESET_CONFIG' });
    };

    // 导出配置
    const exportConfig = (): string => {
        return JSON.stringify(state.currentChart, null, 2);
    };

    // 导入配置
    const importConfig = (config: string) => {
        dispatch({ type: 'IMPORT_CONFIG', payload: config });
    };

    // 切换预览模式
    const togglePreviewMode = () => {
        dispatch({ type: 'TOGGLE_PREVIEW_MODE' });
    };

    // 设置编辑部分
    const setEditingPart = (part: 'config' | 'data') => {
        dispatch({ type: 'SET_EDITING_PART', payload: part });
    };

    // 设置加载状态
    const setLoading = (loading: boolean) => {
        dispatch({ type: 'SET_LOADING', payload: loading });
    };

    // 设置错误信息
    const setError = (error: string | null) => {
        dispatch({ type: 'SET_ERROR', payload: error });
    };

    return {
        state,
        updateChart,
        switchChartType,
        updateData,
        updateDataConfig,
        undo,
        redo,
        resetConfig,
        exportConfig,
        importConfig,
        togglePreviewMode,
        setEditingPart,
        setLoading,
        setError
    };
};

// 编辑器主组件
const Editor: React.FC = () => {
    // 获取状态和操作
    const { state } = useEditor();

    // 使用 Antd Layout 替换 Box
    return (
        <Layout style={{ height: '100%', width: '100%' }}>
            {/* 预览模式 */}
            {state.previewMode ? (
                // 预览模式下，Content 占据整个 Layout
                <Content style={{ padding: 16, overflow: 'auto' }}>
                    <PreviewPanel />
                </Content>
            ) : (
                // 编辑模式
                <>
                    {/* 左侧配置面板 - 使用 Sider */}
                    <Sider
                        width="35%" // 保持宽度比例
                        style={{
                            height: '100%',
                            overflow: 'auto',
                            padding: 16, // 使用 antd 风格的 padding
                            backgroundColor: '#fff', // Sider 默认背景可能不是白色
                            borderRight: '1px solid #f0f0f0' // antd 风格的边框
                        }}
                    >
                        <EditorPanel />
                    </Sider>

                    {/* 右侧预览面板 - 使用 Content */}
                    <Content
                        style={{
                            height: '100%',
                            overflow: 'auto',
                            padding: 16 // 使用 antd 风格的 padding
                        }}
                    >
                        <PreviewPanel />
                    </Content>
                </>
            )}
        </Layout>
    );
};

// 默认导出
export default Editor;

// 导出 EditorContext 以便在 EditorPanel 和 PreviewPanel 中使用
export { EditorContext };